package com.polito.mad.bikeponyapp.list;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.support.v4.content.CursorLoader;

import com.polito.mad.bikeponyapp.persistence.DeliveriesRepository;

public class DeliveryListCursorLoader extends CursorLoader {

	private Cursor currentCursor;
	private DeliveriesRepository repository;
	public DeliveryListCursorLoader(DeliveriesRepository repository,Context context) {
		this(repository,context,null,null,null,null,null);
	}
	
	public DeliveryListCursorLoader(DeliveriesRepository repository,Context context, Uri uri,String[] projection, String selection, String[] selectionArgs,String sortOrder) {
		super(context, uri, projection, selection, selectionArgs, sortOrder);
		this.repository=repository;
	}
	
	@Override
	protected void onStartLoading() {
		if(currentCursor!=null)
		{
			currentCursor.close();
		}
		
		/*
		 * if the cahed objects exists and there at least one object on the cache , 
		 * use the cache to populate the list instead of reloading all items from database.
		 * 
		 * The cache is managed by the repository proxy , 
		 * so we are sure that they represent the latest version of the data
		 */
		
		if(repository.getSessionCachedItems()!=null && !repository.getSessionCachedItems().isEmpty())
			deliverResult(null);
		else
		{
			/* there is no useful cache , and so we should reload the content*/
			currentCursor= repository.getAllAsCursor();	
			deliverResult(currentCursor);
		}
	}
	
	@Override
	protected void onStopLoading() {
		if(currentCursor!=null)
			currentCursor.deactivate();
	}
	@Override
	public void onCanceled(Cursor cursor) {
		currentCursor.close();
	}

}
